﻿using Dapper;
using MediatR;
using MySql.Data.MySqlClient;
using SCM.API.Read.Application.Command.Ledger;
using SCM.ErrorCode;
using SCM.Extensions.Ledger;
using SCM.Infrastructure.Interface;
using System.Text;

namespace SCM.API.Read.Application.Handler.Ledger
{
    public class GetEnterOutHandler : IRequestHandler<GetEnterOutCommand, APIPaging<EnterOutDTO>>
    {
        IDatabaseContext db;

        public GetEnterOutHandler(IDatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIPaging<EnterOutDTO>> Handle(GetEnterOutCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<EnterOutDTO>();

            var countSql = new StringBuilder();
            var sqlBuilder = new StringBuilder();

            sqlBuilder.Append(@"SELECT 
                                        a.id,
                                        a.Code,
                                        a.DateTime,
                                        a.BusinessType,
                                        c.STId,
                                        c.STName,
                                        d.DepotId,
                                        d.DepotName,
                                        a.StockId,
                                        a.IncomingQuantity,
                                        a.IncomingMoney,
                                        a.State,
                                        a.isDel
                                FROM EnterOutModel a  join  DepotModel      d on a.DepotId=d.DepotId
                                                    join Stocking         f on a.StockId=f.Id
                                                    join Stocking_Type c on a.STId=c.STId
                                    WHERE a.IsDel=0  and d.IsDel=0  and f.IsDeleted=0 and c.IsDeleted=0  ");

            countSql.Append(@"SELECT COUNT(a.id)  FROM EnterOutModel a  join  DepotModel      d on a.DepotId=d.DepotId
                                                    join Stocking         f on a.StockId=f.Id
                                                    join Stocking_Type c on a.STId=c.STId
                                    WHERE a.IsDel=0  and d.IsDel=0  and f.IsDeleted=0 and c.IsDeleted=0  ");

            var parameters = new DynamicParameters();

            if (!string.IsNullOrEmpty(request.DepotName))
            {
                sqlBuilder.Append(" AND DepotName LIKE @DepotName ");
                parameters.Add("DepotName", $"%{request.DepotName}%");
                countSql.Append(" AND DepotName LIKE @DepotName ");
            }
            if (!string.IsNullOrEmpty(request.Code))
            {
                sqlBuilder.Append(" AND a.Code LIKE @a.Code ");
                parameters.Add("a.Code", $"%{request.Code}%");
                countSql.Append(" AND a.Code LIKE @a.Code ");
            }
            if (request.BusinessType != null)
            {
                sqlBuilder.Append("AND BusinessType = @BusinessType ");
                parameters.Add("BusinessType", request.BusinessType);
                countSql.Append("AND BusinessType = @BusinessType ");
            }
            if (request.STId != null)
            {
                sqlBuilder.Append("AND c.STId = @c.STId ");
                parameters.Add("c.STId", request.STId);
                countSql.Append("AND c.STId = @c.STId ");
            }
            if (request.DateTime != null)
            {
                DateTime dateOnly = request.DateTime.Value.Date;
                sqlBuilder.Append(" AND CAST(a.DateTime AS DATE) = @DateOnly ");
                parameters.Add("@DateOnly", dateOnly);
                countSql.Append(" AND CAST(a.DateTime AS DATE) = @DateOnly ");
            }

            sqlBuilder.Append("ORDER BY id DESC ");
            sqlBuilder.Append("LIMIT @PageSize OFFSET @Offset ");
            parameters.Add("PageSize", request.PageSize);
            parameters.Add("Offset", (request.PageIndex - 1) * request.PageSize);

           

            var data = await db.DapperConnection.QueryAsync<EnterOutDTO>(sqlBuilder.ToString(), parameters);
            var total = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);

            result.Msg = "显示成功";
            result.Code = APIEnum.Success;
            result.items = data.ToList();
            result.totalCount = total;
            result.totalPage = (int)Math.Ceiling((double)total / request.PageSize);
            return result;
        }
    }
}
